package com.itheima.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //从session中获取当前登录后台管理系统的员工id
    //1.在MyMetaObjectHandler类中注入session对象  2.在填充方法中从session中取出员工id即可

    //1.在MyMetaObjectHandler类中注入session对象
    /*@Autowired
    private HttpSession session;*/

    //插入时填充设置
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("【公共字段自动填充-insert】");

        //2.在填充方法中从session中取出员工id即可
        //Long id = (Long) session.getAttribute("employee");

        //从ThreadLocal中获取共享数据 登录系统的用户id
        Long id = BaseContext.getCurrentId();

        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("createUser",id);

        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("updateUser",id);
    }

    //更新时填充设置
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("MyMetaObjectHandler 线程id="+Thread.currentThread().getId());

        log.info("【公共字段自动填充-update】");

        //2.在填充方法中从session中取出员工id即可
        //Long id = (Long) session.getAttribute("employee");

        //从ThreadLocal中获取共享数据 登录系统的用户id
        Long id = BaseContext.getCurrentId();

        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("updateUser",id);
    }
}
